2023/12/231990字符

事件

import React from 'react';
import ReactDOM from 'react-dom';

ReactDOM.render(<button onClick={() => console.log(123)}>点击</button>, document.getElementById('root'));

React 事件必须以小驼峰命名方式命名,与原生的方法几乎没有差别 在组件调用的标签上使用事件无效,React 只会当做是 props 的属性

事件处理中的 this 指向问题

class MyCopm extends React.Component {
    state = {
        num: 10
    }
    add () {
        this.setState({  // 这里的 this 会指向 undefined
            num: this.state.num + 1
        })
    }

    render () {
        return (<>
            <p>{this.state.num}</p>
            <button onClick={this.add}>加一</button>
        </>)
    }
}

ReactDOM.render(<MyCopm/>, document.getElementById('root'));

通过以下方式来改变 this 指向

import React from 'react';
import ReactDOM from 'react-dom';

class MyCopm extends React.Component {
    constructor () {
        super();
        this.add = this.add.bind(this);  // 1. 改变原型,重新绑定给 this
        this.state = {
            num: 10
        }
    }
    add () {
        this.setState({
            num: this.state.num + 1
        })
    }
    reduce () {
        this.setState({
            num: this.state.num - 1
        })
    }
    ride = () => {  // 3. 通过箭头函数来改变 this
        this.setState({
            num: this.state.num ** 2
        })
    }

    render () {
        return (<>
            <p>{this.state.num}</p>
            <button onClick={this.add}>加一</button>
            <button onClick={this.reduce.bind(this)}>减一</button>
            {/* 2. 直接在绑定事件上改变 this 指向(效率较慢) */}
            <button onClick={this.ride}>开方</button>
        </>)
    }
}

ReactDOM.render(<MyCopm/>, document.getElementById('root'));